package topsun.rms.web;

import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import topsun.framework.utility.HqlFilter;
import topsun.framework.utility.StringHelper;
import topsun.framework.utility.excel.ExcelUtils;
import topsun.framework.utility.excel.JsGridReportBase;
import topsun.framework.utility.excel.TableData;
import topsun.rms.model.Pager;
import topsun.rms.model.RetJson;
import topsun.rms.services.IBaseService;
import topsun.rms.utility.WriteJsonUtil;

/**
 * 基于esayui的基础 Controller
 * 
 * @author yuxiaobei
 *
 * @param <T>
 */
@SuppressWarnings("rawtypes")
public class BaseController<T> 
{
	private static final Logger logger = Logger.getLogger(BaseController.class);
	protected Hashtable<String, String> paramList = new Hashtable<>();

	protected int page = 1;
	protected int rows = 10;
	protected String sort;
	protected String order = "asc";
	protected String q;

	protected String id;
	protected String ids;
	protected T data;
	
	protected String title = "export";
	protected String[] hearders = new String[] {"编号", "名称"};
	protected String[] fields  = new String[] {"id", "name"};
	
	protected String idtype = "0";
	protected String idname = "id";
	

	public String getIdname() {
		return idname;
	}
	public void setIdname(String idname) {
		this.idname = idname;
	}
	public String getIdtype() {
		return idtype;
	}
	public void setIdtype(String idtype) {
		this.idtype = idtype;
	}
	public Hashtable<String, String> getParamList() {
		return paramList;
	}
	public void setParamList(Hashtable<String, String> paramList) {
		this.paramList = paramList;
	}
	public String[] getHearders() {
		return hearders;
	}
	public void setHearders(String[] hearders) {
		this.hearders = hearders;
	}
	public String[] getFields() {
		return fields;
	}
	public void setFields(String[] fields) {
		this.fields = fields;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public static Logger getLogger() {
		return logger;
	}
	public IBaseService<T> getService() {
		return service;
	}

	protected IBaseService<T> service;// 业务逻辑
	
	/**
	 * 继承BaseController的Controller需要先设置这个方法，使其获得当前Controller的业务服务
	 * 
	 * @param service
	 */
	@Resource
	public void setService(IBaseService<T> service) 
	{
		this.service = service;
	}
	protected void resetParams()
	{
		page = 1;
		rows = 10;
		sort = "";
		order = "";
		ids = "";
		data = null;
		paramList.clear();
		
		idtype = "0";
	}
	protected void parseRequest(HttpServletRequest request)
	{
		resetParams();
		
		Enumeration enu=request.getParameterNames();  
		while(enu.hasMoreElements())
		{  
			String paraName=(String)enu.nextElement();
			SetParamValue(paraName,request.getParameter(paraName));
		}  
		
		//idtype
		if(paramList.containsKey("idtype"))
		{
			setIdtype(paramList.get("idtype"));
		}
		
		//idname
		if(paramList.containsKey("idname"))
		{
			setIdname(paramList.get("idname"));
		}
		
		//id
		if(paramList.containsKey("id"))
		{
			setId(paramList.get("id"));
		}
		
		//ids
		if(paramList.containsKey("ids"))
		{
			setIds(paramList.get("ids"));
		}
		//page
		if(paramList.containsKey("page"))
		{
			try
			{
				setPage(Integer.parseInt(paramList.get("page")));
			}
			catch(NumberFormatException ex)
			{
				logger.info("page invalid");
			}
		}
		//rows
		if(paramList.containsKey("rows"))
		{
			try
			{
				setRows(Integer.parseInt(paramList.get("rows")));
			}
			catch(NumberFormatException ex)
			{
				logger.info("rows invalid");
			}
		}
		//sort
		if(paramList.containsKey("sort"))
		{
			setSort(paramList.get("sort"));
		}
		//order
		if(paramList.containsKey("order"))
		{
			setOrder(paramList.get("order"));
		}
		
	}
	
	public void SetParamValue(String paramString1, String paramString2) 
	{
		if (!StringHelper.IsNullOrEmpty(paramString1.trim()) && !paramList.containsKey(paramString1.trim().toLowerCase()))
	    {
	      paramList.put(paramString1.toLowerCase(), paramString2);
	    }
	}
	
	public String getId() 
	{
		return id;
	}

	public void setId(String id) 
	{
		this.id = id;
	}

	public String getIds() 
	{
		return ids;
	}

	public void setIds(String ids) 
	{
		this.ids = ids;
	}

	public T getData() 
	{
		return data;
	}

	public void setData(T data) 
	{
		this.data = data;
	}

	public int getPage() 
	{
		return page;
	}

	public void setPage(int page) 
	{
		this.page = page;
	}

	public int getRows() 
	{
		return rows;
	}

	public void setRows(int rows) 
	{
		this.rows = rows;
	}

	public String getSort() 
	{
		return sort;
	}

	public void setSort(String sort) 
	{
		this.sort = sort;
	}

	public String getOrder() 
	{
		return order;
	}

	public void setOrder(String order) 
	{
		this.order = order;
	}

	public String getQ() 
	{
		return q;
	}

	public void setQ(String q) 
	{
		this.q = q;
	}
	
	/**
	 * 将对象转换成JSON字符串，并响应回前台
	 * 
	 * @param object
	 * @param includesProperties
	 *            需要转换的属性
	 * @param excludesProperties
	 *            不需要转换的属性
	 */
/*	public void writeJsonByFilter(Object object, String[] includesProperties, String[] excludesProperties, HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			FastjsonFilter filter = new FastjsonFilter();
			if (excludesProperties != null && excludesProperties.length > 0)
			{
				filter.getExcludes().addAll(Arrays.<String> asList(excludesProperties));
			}
			if (includesProperties != null && includesProperties.length > 0)
			{
				filter.getIncludes().addAll(Arrays.<String> asList(includesProperties));
			}
			
			String retJson;
			String User_Agent = request.getHeader("User-Agent");
			if (StringUtils.indexOf(User_Agent, "MSIE 6") > -1) 
			{
				retJson = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat, 
						SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.BrowserCompatible);
			} else 
			{
				retJson = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat, 
						SerializerFeature.DisableCircularReferenceDetect);
			}
			response.setContentType("text/html;charset=utf-8");
			System.out.println(retJson);
			response.getWriter().write(retJson);
			response.getWriter().flush();
			response.getWriter().close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}*/

	/**
	 * 将对象转换成JSON字符串，并响应回前台
	 * 
	 * @param object
	 * @throws IOException
	 */
	public void writeJson(Object object, HttpServletRequest request, HttpServletResponse response) 
	{
		WriteJsonUtil.writeJsonByFilter(object, null, null, request, response);
	}

	/**
	 * 将对象转换成JSON字符串，并响应回前台
	 * 
	 * @param object
	 * @param includesProperties
	 *            需要转换的属性
	 */
	public void writeJsonByIncludesProperties(Object object, String[] includesProperties, HttpServletRequest request, HttpServletResponse response) 
	{
		WriteJsonUtil.writeJsonByFilter(object, includesProperties, null, request, response);
	}

	/**
	 * 将对象转换成JSON字符串，并响应回前台
	 * 
	 * @param object
	 * @param excludesProperties
	 *            不需要转换的属性
	 */
	public void writeJsonByExcludesProperties(Object object, String[] excludesProperties, HttpServletRequest request, HttpServletResponse response) 
	{
		WriteJsonUtil.writeJsonByFilter(object, null, excludesProperties, request, response);
	}

	/**
	 * 获得一个对象
	 */
	@RequestMapping(value = "/getbyid", method = RequestMethod.POST)
	protected void getById(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		RetJson retJson = new RetJson();
		
		if( id ==null || StringUtils.isBlank(id))
		{
			retJson.setSuccess(false);
			retJson.setMsg("id 为空");
		}
		else
		{
			if("1".equals(idtype))
				retJson.setObj(service.getById(Integer.parseInt(id)));
			else
				retJson.setObj(service.getById(id));
			
			retJson.setSuccess(true);
		}
		
		writeJson(retJson,request,response);
	}
	

	
	/**
	 * 查找一批对象
	 */
	public void find(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		HqlFilter hqlFilter = new HqlFilter(request);
		writeJson(service.findByFilter(hqlFilter, page, rows), request, response);
	}

	/**
	 * 查找所有对象
	 */
	@RequestMapping(value = "/listall", method = RequestMethod.POST)
	protected void findAll(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		writeJson(service.find(), request, response);
	}
	
	/**
	 * 查找所有对象(有排序或其他条件)
	 */
	@RequestMapping(value = "/listallex", method = RequestMethod.POST)
	protected void findAllEx(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		HqlFilter hqlFilter = new HqlFilter(request);
		writeJson(service.findByFilter(hqlFilter), request, response);
	}

	/**
	 * 查找分页后的grid
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	protected void grid(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		Pager pager = new Pager();
		HqlFilter hqlFilter = new HqlFilter(request);
		pager.setTotal(service.countByFilter(hqlFilter));
		pager.setRows(service.findByFilter(hqlFilter, page, rows));
		writeJson(pager, request, response);
	}

	/**
	 * 查找grid所有数据，不分页
	 */
	public void gridAll(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		Pager pager = new Pager();
		HqlFilter hqlFilter = new HqlFilter(request);
		List l = service.findByFilter(hqlFilter);
		pager.setTotal((long) l.size());
		pager.setRows(l);
		writeJson(pager, request, response);
	}


	/**
	 * 保存一个对象
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)   
	public void save(HttpEntity<T> model, HttpServletRequest request, HttpServletResponse response)
	{
		parseRequest(request);
		
		RetJson json = new RetJson();
	    json.setObj(service.save(model.getBody()));
		json.setSuccess(true);
		json.setMsg("添加成功！");
		writeJson(json, request, response);
	}

	/**
	 * 更新一个对象
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)   
	protected void update(HttpEntity<T> model, HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		RetJson json = new RetJson();
		service.update(model.getBody());
		json.setSuccess(true);
		json.setMsg("更新成功！");
		writeJson(json, request, response);
	}
	
	/**
	 * 更新一个对象 updateByParams
	 */
	@RequestMapping(value = "/updateByParams", method = RequestMethod.POST)   
	protected void updateByParams(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		RetJson retJson = new RetJson();
		String[] ids2 = ids.split(",");
		
		if(ids2.length == 0)
		{
			retJson.setMsg("id 为空");
		}
		else
		{
			for(int i = 0;i<ids2.length;i++)
			{
				HqlFilter hqlFilter = new HqlFilter(request);
				String strQurey = "QUERY_t#"+ idname ;
				strQurey += "1".equals(idtype) ?  "_I_EQ" : "_S_EQ";
				hqlFilter.addFilter(strQurey,ids2[i]);
				service.updateByParams(hqlFilter);
			}
			
			retJson.setSuccess(true);
		}
		
		writeJson(retJson,request,response);
	}

	/**
	 * 删除对象
	 */
	@RequestMapping(value = "/remove", method = RequestMethod.POST)   
	protected void delete(HttpServletRequest request, HttpServletResponse response) 
	{
		parseRequest(request);
		
		RetJson retJson = new RetJson();
		String[] ids2 = ids.split(",");
		if(ids2.length == 0)
		{
			retJson.setMsg("id 为空");
		}
		else
		{
			for(int i = 0;i<ids2.length;i++)
			{
				if("1".equals(idtype))
					service.delete(Integer.parseInt(ids2[i]));
				else
				service.delete(ids2[i]);
			}
			retJson.setSuccess(true);
			retJson.setObj("");
			retJson.setMsg("");
		}
		
		writeJson(retJson,request,response);
	}
	
	@RequestMapping(value = "/exportexcel", method = RequestMethod.GET)
	public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		parseRequest(request);
		response.setContentType("application/msexcel;charset=GBK");
        
		HqlFilter hqlFilter = new HqlFilter(request);
		List<T> list = null;
		if(paramList.containsKey("exportmodel") && paramList.get("exportmodel").equals("all"))
		{
			list = service.findByFilter(hqlFilter);
		}
		else
		{
			list =  service.findByFilter(hqlFilter, page, rows);
		}
        if(list == null || list.size() == 0) return;
        TableData td = ExcelUtils.createTableData(list, ExcelUtils.createTableHeader(hearders),fields);
        JsGridReportBase report = new JsGridReportBase(request, response);
        report.exportToExcel(title, "", td);
	}
	
	protected void excuteSuccess(HttpServletRequest request, HttpServletResponse response)
	{
		RetJson retJson = new RetJson();
		retJson.setSuccess(true);
		writeJson(retJson,request,response);
	}
}
